package com.xj.zhihudemo.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xj.zhihudemo.R;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Xujing on 16/7/27.
 */

public class ScrollBanner extends RelativeLayout {

    private static final int RMP = LayoutParams.MATCH_PARENT;
    private static final int RWC = LayoutParams.WRAP_CONTENT;
    private static final int LWC = LinearLayout.LayoutParams.WRAP_CONTENT;
    private static final int WHAT_AUTO_PLAY = 1000;
    //    指示器位置
    private final static int LEFT = 0;
    private final static int CENTER = 1;
    private final static int RIGHT = 2;

    /**
     * 是否只有一张图片
     */
    private boolean mIsOneImg;

    /**
     * 指示器位置默认居中
     */
    private int mIndicatorLocation = CENTER;

    /**
     * 是否显示指示器,默认显示
     */
    private boolean mIndicatorIsShow;
    /**
     * 是否自动播放，默认播放
     */
    private boolean isAutoPlaying;

    /**
     * 是否正在播放播放
     */
    private boolean mIsPlaying;
    /**
     * 播放间隔时间
     */
    private int mAutoPlayingDelay;
    /**
     * 是否加载网络图片
     */
    private boolean mIsImageUrl = false;
    //当前页面位置
    private int mCurrentPosition;
    //指示点资源
    private int mPointDrawableResId = R.drawable.selector_bgabanner_point;
    //指示容器背景
    private Drawable mPointContainerBackgroundDrawable;
    //指示容器布局规则
    private LayoutParams mPointRealContainerLp;
    //指示器布局
    private LinearLayout mPointRealContainerLl;

    //本地图片资源
    private List<Integer> mImages;
    //网络图片资源
    private List<String> mImageUrls = new ArrayList<>();
    private ViewPager mViewPager;

    /**
     * 自动播放线程
     */
    private Handler mAutoPlayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mCurrentPosition++;
            mViewPager.setCurrentItem(mCurrentPosition);
            mAutoPlayHandler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, mAutoPlayingDelay);
        }
    };
    /**
     * ViewPager选择
     */
    private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (mIsImageUrl) {
                mCurrentPosition = position % (mImageUrls.size() + 2);

            } else {
                mCurrentPosition = position % (mImages.size() + 2);
            }
            switchToPoint(toRealPosition(mCurrentPosition));


        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                int current = mViewPager.getCurrentItem();
                int lastReal = mViewPager.getAdapter().getCount() - 2;
                if (current == 0) {
                    mViewPager.setCurrentItem(lastReal, false);
                } else if (current == lastReal + 1) {
                    mViewPager.setCurrentItem(1, false);
                }
            }

        }
    };
    private OnItemClickListener mOnItemClickListener;

    /**
     * @param context 构造方法
     */
    public ScrollBanner(Context context) {
        this(context, null);
    }

    /**
     * @param context
     * @param attrs   构造方法
     */
    public ScrollBanner(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public ScrollBanner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //对属性值进行初始化
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScrollViewPager);
        int n = typedArray.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = typedArray.getIndex(i);
            if (attr == R.styleable.ScrollViewPager_isAutoPlaying) {
                isAutoPlaying = typedArray.getBoolean(attr, true);
            } else if (attr == R.styleable.ScrollViewPager_indicatorLocation) {
                mIndicatorLocation = typedArray.getInt(attr, CENTER);
            } else if (attr == R.styleable.ScrollViewPager_isIndicatorShow) {
                mIndicatorIsShow = typedArray.getBoolean(attr, true);
            } else {
                mAutoPlayingDelay = typedArray.getInt(attr, 3000);
            }
        }
        typedArray.recycle();
        setLayout(context);
    }

    /**
     * @param context 设置布局页面
     */
    private void setLayout(Context context) {
        mViewPager = new ViewPager(context);
        // 关闭边界回弹效果
        setOverScrollMode(OVER_SCROLL_NEVER);
        //  设置指示器布局
        if (mPointContainerBackgroundDrawable == null) {
            mPointContainerBackgroundDrawable = new ColorDrawable(Color.parseColor("#44ffffff"));
        }
//将ViewPager添加至FrameLayout中
        addView(mViewPager, new WindowManager.LayoutParams(RMP, RMP));
        //  设置指示器背景容器
        RelativeLayout pointContainerRl = new RelativeLayout(context);
        if (Build.VERSION.SDK_INT >= 16) {
            pointContainerRl.setBackground(mPointContainerBackgroundDrawable);
        } else {
            pointContainerRl.setBackgroundDrawable(mPointContainerBackgroundDrawable);
        }

//        设置内边距
        pointContainerRl.setPadding(25, 15, 25, 15);
//        设置指示器容器布局以及位置


        LayoutParams pointContainerLp = new LayoutParams(RMP, RWC);
        pointContainerLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        //将指示器布局加载至指示器容器里面
        addView(pointContainerRl, pointContainerLp);


//      设置指示器LinearLayout
        mPointRealContainerLl = new LinearLayout(context);
        mPointRealContainerLl.setOrientation(LinearLayout.HORIZONTAL);
        mPointRealContainerLp = new LayoutParams(RWC, RWC);
        pointContainerRl.addView(mPointRealContainerLl, mPointRealContainerLp);

//        设置指示器是否可见
        if (mPointRealContainerLl != null) {
            if (mIndicatorIsShow) {
                mPointRealContainerLl.setVisibility(VISIBLE);
            } else {
                mPointRealContainerLl.setVisibility(INVISIBLE);
            }
        }
//        设置指示器布局位置
        switch (mIndicatorLocation) {
            case CENTER:
                mPointRealContainerLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
                break;
            case LEFT:
                mPointRealContainerLp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                break;
            case RIGHT:
                mPointRealContainerLp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        }

    }


    public void setAutoPlaying(boolean isAutoPlaying) {
        this.isAutoPlaying = isAutoPlaying;
    }

    public void setDelayTime(int time) {
        this.mAutoPlayingDelay = time;
    }


    /**
     * 加载本地图片
     *
     * @param images
     */
    public void setImages(List<Integer> images) {
        mIsImageUrl = false;
        this.mImages = images;
        if (images.size() <= 1) {
            mIsOneImg = true;
        }
        initViewPager();
    }

    public void setImagesUrl(List<String> urls) {

        mIsImageUrl = true;

        mImageUrls.clear();
        mImageUrls.addAll(urls);
        if (mImageUrls.size() <= 1) {
            mIsOneImg = true;

        }
        initViewPager();
    }

    /**
     * 添加指示点
     */
    public void initPointS() {
        mPointRealContainerLl.removeAllViews();
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LWC, LWC);
        lp.setMargins(10, 8, 10, 8);
        ImageView imageView;
        int length = mIsImageUrl ? mImageUrls.size() : mImages.size();
        for (int i = 0; i < length; i++) {
            imageView = new ImageView(getContext());
            imageView.setLayoutParams(lp);
            imageView.setImageResource(mPointDrawableResId);
            mPointRealContainerLl.addView(imageView);
        }
        switchToPoint(0);
    }

    /**
     * 切换指示器
     *
     * @param currentPoint
     */
    private void switchToPoint(final int currentPoint) {
        for (int i = 0; i < mPointRealContainerLl.getChildCount(); i++) {

            mPointRealContainerLl.getChildAt(i).setEnabled(false);
        }
        mPointRealContainerLl.getChildAt(currentPoint).setEnabled(true);
    }

    /**
     * 手势操作
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!mIsOneImg && isAutoPlaying) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    stopAutoPlay();
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_OUTSIDE:
                    startAutoPlay();
                    break;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        if (!mIsOneImg) {
            initPointS();
        }
        ScrollViewAdapter mAdapter = new ScrollViewAdapter();
        mViewPager.setAdapter(mAdapter);
        mViewPager.addOnPageChangeListener(mOnPageChangeListener);

        mViewPager.setCurrentItem(1, false);
        if (!mIsOneImg) {
            startAutoPlay();
        }
    }

    /**
     * 返回真实的位置
     *
     * @param position
     * @return
     */
    private int toRealPosition(int position) {
        int realPosition;
        if (mIsImageUrl) {
            realPosition = (position - 1) % mImageUrls.size();
            if (realPosition < 0)
                realPosition += mImageUrls.size();
        } else {
            realPosition = (position - 1) % mImages.size();
            if (realPosition < 0)
                realPosition += mImages.size();
        }

        return realPosition;
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    /**
     * 开始播放
     */
    public void startAutoPlay() {
        if (isAutoPlaying && !mIsPlaying) {
            mIsPlaying = true;
            mAutoPlayHandler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, mAutoPlayingDelay);
        }
    }

    /**
     * 停止播放
     */
    public void stopAutoPlay() {
        if (isAutoPlaying && mIsPlaying) {
            mIsPlaying = false;
            mAutoPlayHandler.removeMessages(WHAT_AUTO_PLAY);
        }

    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    private class ScrollViewAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (mIsOneImg) {
                return 1;
            }
            if (mIsImageUrl) {
                return mImageUrls.size() + 2;
            }
            return mImages.size() + 2;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            SimpleDraweeView imageView = new SimpleDraweeView(getContext());
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(toRealPosition(position));
                    }
                }
            });
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (mIsImageUrl) {

                imageView.setImageURI(mImageUrls.get(toRealPosition(position)));
//                imageView.setColorFilter(R.color.translucent_status);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            } else {
                imageView.setImageResource(mImages.get(toRealPosition(position)));
            }
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            if (object != null) {
                object = null;
            }
        }
    }
}

